<template>
  <div>
    <el-col :span="24">
      <el-card style="height: 300px;">
        {{ chartTitle }}
        <div :id="'predictChartLineBox'+id" style="height: 300px;"></div>
      </el-card>
    </el-col>
  </div>
</template>

<script>
  import {getNodesByBrowsePath, queryCurrentRawValueByUri, queryHistoryRawValueByUri} from "../../api/faultWarning";

  export default {
    name: "ChartByUri",
    data() {
      return {
        timeInterval: 300000,
        unit: '',
        min: 0,
        max: 100,
      }
    },
    props: ['id', 'uri', 'chartTitle', 'token', 'paramName'],
    mounted() {
      this.start();
    },
    beforeDestroy() {
      // console.log("clearInterval");
      clearInterval(this.interval);
    },
    methods: {
      start() {
        this.firstFlag = true
        let param = {
          "depth": 2,
          "forward": true,
          "id": this.uri.split("/")[2]
        };

        getNodesByBrowsePath(this.token, param).then((res) => {
          if (res) {
            let nodes = res.data.result[0].children;
            let nodesDict = {};
            for (let item of nodes) {
              nodesDict[item.name] = item;
            }
            this.predUri = nodesDict["预测值"].uri;
            console.log('预警this.predUri', this.predUri);
            let children = nodesDict["关键参数"].children;
            let realUri;
            for (let i = 0; i < children.length; i++) {
              let child = children[i];
              if (child.uri.substring(0, 8) === '/Project' && this.paramName.indexOf(child.name) !== -1) {
                this.realUri = child.uri;
                // console.log(child);
                break;
              }
            }
            this.predict();
            this.interval = setInterval(this.predict, 5000);
          }
        });
      },
      queryHistory(realUri, predUri, timeInterval) {
        let now = new Date().getTime();
        console.log(now)
        let param = {
          "nodes": [
            {
              "browsePath": realUri
            },
            {
              "browsePath": predUri
            }
          ],
          "detail": {
            "maxSizePerNode": 100,
            "returnBounds": false,
            "startTime": now - timeInterval,
            "endTime": now + timeInterval
          }
        };
        return queryHistoryRawValueByUri(param);
      },
      predict() {
        if (this.firstFlag) {
          this.firstFlag = false;
          console.log(this.realUri, this.predUri);
          this.queryHistory(this.realUri, this.predUri, this.timeInterval).then(res => {
            // console.log(res.data)
            let dataset;
            try {
              dataset = {
                data: res.data.result[0].historyData,
                prediction: res.data.result[1].historyData
              }
            } catch (e) {
              // console.log(e)
              this.firstFlag = true;
              return;
            }
            this.drawChart(dataset)
          })
        } else {
          let param = [this.realUri, this.predUri]
          queryCurrentRawValueByUri(param).then(res => {
            let dataset = {
              data: res.data.result[0],
              prediction: res.data.result[1]
            };
            console.log("dataset", dataset);
            this.addChartData(dataset)
          })
        }
      },
      drawChart(dataset) {
        const chartDom = document.getElementById('predictChartLineBox' + this.id);
        this.myChart = this.$echarts.init(chartDom);

        this.realData = dataset.data.map(item => [item.t, item.v.toFixed(2)])
        this.predictData = dataset.prediction.map(item => [item.t, item.v.toFixed(2)])
        if (this.paramName == "炉膛温度预警") {
          this.unit = '单位：℃';
          this.min = 0;
          this.max = 1200
        } else if (this.paramName == "炉膛压力预警") {
          this.unit = '单位：Pa';
          this.min = -150;
          this.max = 50;
        } else if (this.paramName == "鼓风风量预警") {
          this.unit = '单位：m3/h';
          this.min = 0;
          this.max = 20000;
        }

        this.option = {
          tooltip: {
            trigger: 'axis',
          },
          legend: {
            data: ['真实值', '预测值']
          },
          xAxis: {
            type: "time",
            axisLine: {
              symbol: ['none', 'arrow'],
              symbolOffset: 5,
              symbolSize: [10, 10]
            },
            axisTick: false
          },
          yAxis: [{
            scale: true,
            min: this.min,
            max: this.max
          }, {
            position: 'right',
            name: this.unit,
            axisLine: {
              show: false
            }
          }],
          series: [{
            name: '真实值',
            data: this.realData,
            type: 'line',
            symbolSize: 5,
            symbol: 'circle',
            itemStyle: {
              normal: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: '#fe6431'
                }, {
                  offset: 1,
                  color: '#f9f560'
                }])
              }
            },
            lineStyle: {
              width: 2,
            }
          }, {
            name: '预测值',
            data: this.predictData,
            type: 'line',
            symbolSize: 5,
            symbol: 'circle',
            itemStyle: {
              normal: {
                color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: '#25e558'
                }, {
                  offset: 1,
                  color: '#62c7f6'
                }])
              }
            },
            lineStyle: {
              width: 2,
            }
          }]
        };

        this.myChart.setOption(this.option);
      },

      addChartData(dataset) {
        let time = new Date().getTime() - this.timeInterval;
        let data = dataset.data;
        let predict = dataset.prediction;
        for (let i = 0; i < this.realData.length; i++) {
          if (this.realData[i][0] > time) {
            this.realData.splice(0, i);
            break;
          }
        }
        for (let i = 0; i < this.predictData.length; i++) {
          if (this.predictData[i][0] > time) {
            this.predictData.splice(0, i);
            break;
          }
        }
        if (this.realData[this.realData.length - 1][0] !== data.t) {
          this.realData.push([data.t, data.v.toFixed(2)])
        }
        if (this.predictData[this.predictData.length - 1][0] !== predict.t) {
          this.predictData.push([predict.t, predict.v.toFixed(2)])
        }

        this.myChart.setOption(this.option);
      }
    }
  }
</script>

<style scoped>

</style>
